package com.rocketmq.listener;

import com.rocketmq.dao.IOrderMapper;
import com.rocketmq.dao.IProductMapper;
import com.rocketmq.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "overtime", consumerGroup = "consumer_grp_02")
public class PayOvertimeListener implements RocketMQListener<Order> {

    @Autowired
    private IOrderMapper orderMapper;

    @Autowired
    private IProductMapper productMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Order order) {
        // 处理broker推送过来的消息
        //判断订单是否已支付
        Order orderInfoByOrderId = orderMapper.getOrderInfoByOrderId(order.getId());
        if (orderInfoByOrderId.getStatus() == 0) {
            System.out.println("取消订单");
            //将订单取消
            order.setStatus(2);
            orderMapper.updateStatus(order.getId(), order.getStatus());

            //恢复库存
            productMapper.addStore(order.getProductId());

            //更新缓存中的数据
//        Object o = redisTemplate.opsForValue().get("product_" + produce.getId());
            redisTemplate.opsForValue().increment("product_" + order.getProductId(), 1);
        }

    }
}
